// MainDlg.cpp : implementation of the CMainDlg class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "resource.h"

#include "aboutdlg.h"
#include "MainDlg.h"
#include "UrlDialog.h"

#include "Path.h"

#include <atltime.h>

//////////////////////////////////////////////////////////////////////////
#define     TIMER_GETPOS    1

//////////////////////////////////////////////////////////////////////////

BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN)
    {
        UINT nRepCnt = (UINT)pMsg->lParam & 0xFFFF;
        UINT nFlags = (UINT)((pMsg->lParam & 0xFFFF0000) >> 16);

        OnKeyDown(pMsg->wParam, nRepCnt, nFlags);
    }

	return CWindow::IsDialogMessage(pMsg);
}

BOOL CMainDlg::OnIdle()
{
	return FALSE;
}

LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	// center the dialog on the screen
	CenterWindow();

	// set icons
	HICON hIcon = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON));
	SetIcon(hIcon, TRUE);
	HICON hIconSmall = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON));
	SetIcon(hIconSmall, FALSE);

	// register object for message filtering and idle updates
	CMessageLoop* pLoop = _Module.GetMessageLoop();
	ATLASSERT(pLoop != NULL);
	pLoop->AddMessageFilter(this);
	pLoop->AddIdleHandler(this);

	UIAddChildWindowContainer(m_hWnd);

    init();

	return TRUE;
}

LRESULT CMainDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	// unregister message filtering and idle updates
	CMessageLoop* pLoop = _Module.GetMessageLoop();
	ATLASSERT(pLoop != NULL);
	pLoop->RemoveMessageFilter(this);
	pLoop->RemoveIdleHandler(this);

    uninit();

	return 0;
}

LRESULT CMainDlg::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	CAboutDlg dlg;
	dlg.DoModal();
	return 0;
}

LRESULT CMainDlg::OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	// TODO: Add validation code 
	CloseDialog(wID);
	return 0;
}

LRESULT CMainDlg::OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	CloseDialog(wID);
	return 0;
}

void CMainDlg::CloseDialog(int nVal)
{
	DestroyWindow();
	::PostQuitMessage(nVal);
}



void CMainDlg::init()
{
    av::LitePlayerFactory::startup();

    m_player = av::LitePlayerFactory::create(m_hWnd);

    std::string workDir = comn::Path::getWorkDir();
    std::string logoPath = comn::Path::join(workDir, "logo.png");
    m_player->setImage(logoPath.c_str());
	
	m_player->setProp(MEDIA_SOURCE_PROP_PROBESIZE, "1024");

    onPlayerOpenClose(false);

    //layoutControl();

    //OsdOverlay osd;
    //memset(&osd, 0, sizeof(osd));
    //osd.type = kOsdText;
    //osd.alpha = 0xff;
    //strcpy_s(osd.source.text.str, "LitePlayer");
    //osd.source.text.color = RGB(255, 0, 0);
    //osd.source.text.font.size = 20;

    //m_player->setOverlay(0, &osd);
}

void CMainDlg::uninit()
{
    closeFile();

    av::LitePlayerFactory::destroy(m_player);
    m_player = NULL;

    av::LitePlayerFactory::cleanup();
}

bool CMainDlg::isOpen()
{
    return (m_player != NULL);
}

bool CMainDlg::openFile(const CString& filepath)
{
    if (m_player->getState() == av::STATE_PLAYING)
    {
        closeFile();
    }

    CPath path(filepath);
    path.StripPath();

    int ret = m_player->open(filepath, "");
    if (ret == 0)
    {
        m_url = filepath;

        onPlayerOpenClose(true);

        play();

        SetTimer(TIMER_GETPOS, 1000, NULL);
    }

    return true;
}

void CMainDlg::closeFile()
{
    if (m_player)
    {
        m_player->stop();
    }

    onPlayerOpenClose(false);

    KillTimer(TIMER_GETPOS);
}

LRESULT CMainDlg::OnFileOpen(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    CString filepath = chooseFile();
    if (filepath.IsEmpty())
    {
        return 0;
    }

    openFile(filepath);
    return 0;
}


LRESULT CMainDlg::OnFileClose(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    closeFile();
    return 0;
}

LRESULT CMainDlg::OnBnClickedPlay(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    pause();

    return 0;
}

LRESULT CMainDlg::OnBnClickedPause(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    pause();

    return 0;
}

LRESULT CMainDlg::OnBnClickedStop(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    stop();

    return 0;
}

LRESULT CMainDlg::OnBnClickedSlow(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    return 0;
}

LRESULT CMainDlg::OnBnClickedFast(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    return 0;
}

LRESULT CMainDlg::OnBnClickedFullscreen(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    bool full = m_player->isFullscreen();
    m_player->setFullscreen(!full);

    return 0;
}


LRESULT CMainDlg::OnSnap(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    CString filepath;
    CTime t = CTime::GetCurrentTime();
    filepath = t.Format("%Y-%m-%dT%H_%M_%S.bmp");

    std::string snapDir = getSnapDir();
    std::string filename = comn::Path::join(snapDir, filepath.GetString());
    
    m_player->snap(filename.c_str());
    return 0;
}

LRESULT CMainDlg::OnFileOpenUrl(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    CUrlDialog dialog;
    if (IDOK == dialog.DoModal())
    {
        CString url = dialog.getUrl();
        openFile(url);
    }

    return 0;
}

LRESULT CMainDlg::OnControl(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    return 0;
}

LRESULT CMainDlg::OnVolumeDec(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    float volume = m_player->getVolume();
    volume = volume - 0.1f;
    if (volume < 0)
    {
        volume = 0;
    }

    m_player->setVolume(volume);

    return 0;
}

LRESULT CMainDlg::OnVolumeInc(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    float volume = m_player->getVolume();
    volume += 0.1f;
    if (volume > 1.0)
    {
        volume = 1.0;
    }

    m_player->setVolume(volume);

    return 0;
}

LRESULT CMainDlg::OnVolumeMute(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    bool muted = m_player->isMute();
    m_player->setMute(!muted);

    return 0;
}

LRESULT CMainDlg::OnRatioFit(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    m_player->setRatio(-1, -1);
    return 0;
}

LRESULT CMainDlg::OnRatioDefault(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    m_player->setRatio(0, 0);
    return 0;
}

LRESULT CMainDlg::OnRatio1V1(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    m_player->setRatio(1, 1);
    return 0;
}

LRESULT CMainDlg::OnRatio16V9(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    m_player->setRatio(16, 9);
    return 0;
}

LRESULT CMainDlg::OnRatio4V3(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    if (!isOpen())
    {
        return 0;
    }

    m_player->setRatio(4, 3);

    return 0;
}

void CMainDlg::OnSize(UINT nType, const CSize& size)
{
    //layoutControl();

    if (m_player)
    {
        CRect rc;
        GetClientRect(&rc);


    }
}

BOOL CMainDlg::OnEraseBkgnd(HDC hdc)
{
    return TRUE;
}

void CMainDlg::OnDropFiles(HDROP hDrop)
{
    char filename[MAX_PATH];
    UINT count = DragQueryFile(hDrop, 0, filename, MAX_PATH);
    if (count != 0)
    {
        openFile(filename);
    }
}

void CMainDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    if (nChar == VK_DOWN)
    {
        BOOL handled = FALSE;
        OnVolumeDec(0, 0, NULL, handled);
    }
    else if (nChar == VK_UP)
    {
        BOOL handled = FALSE;
        OnVolumeInc(0, 0, NULL, handled);
    }
}

void CMainDlg::play()
{
    m_player->play();

    onPlayerPause(false);
}

void CMainDlg::pause()
{
    bool paused = (m_player->getState() == av::STATE_PAUSED);
    if (paused)
    {
        m_player->play();
    }
    else
    {
        m_player->pause();
    }

    paused = (m_player->getState() == av::STATE_PAUSED);
    onPlayerPause(paused);
}

void CMainDlg::stop()
{
    m_player->stop();
    m_player->close();

    //onPlayerPlayStop(false);
    onPlayerOpenClose(false);
}

void CMainDlg::onPlayerOpenClose(bool opened)
{
    //m_btnPlay.EnableWindow(opened);
    //m_btnPause.EnableWindow(opened);
    //m_btnStop.EnableWindow(opened);
    //m_btnFast.EnableWindow(opened);
    //m_btnSlow.EnableWindow(opened);
    //m_btnFull.EnableWindow(opened);

    //m_slider.SetPos(0);

    //m_videoWnd.Invalidate(true);
    //m_videoWnd.ShowWindow(SW_HIDE);
    //m_videoWnd.ShowWindow(SW_SHOW);
}


void CMainDlg::onPlayerPause(bool paused)
{
    //m_btnPlay.EnableWindow(paused);
    //m_btnPause.EnableWindow(!paused);

}


CString CMainDlg::chooseFile()
{
    char szFilter[] = //_T("Movie Files (*.mp4)|*.mp4|")
        _T("All Files (*.*)|*.*||");

    CFileDialog dlg(TRUE, NULL, "", 
        OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT);

    if (dlg.DoModal() != IDOK)
    {
        return "";
    }

    CString filePath;
    filePath = dlg.m_szFileName;
    
    return filePath;
}

std::string CMainDlg::getSnapDir()
{
    std::string workDir = comn::Path::getWorkDir();
    std::string dir = comn::Path::join(workDir, "picture");
    comn::Path::createDirectories(dir);
    return dir;
}

